const db = uniCloud.database()
const dbCmd = db.command;
module.exports = {
	main: async (event) => {
		let {
			res,
			data,
			action
		} = event;
		switch (action) {
			case 'queryById':
				res.data = await getDataById(data);
				break;
			case 'add':
				res = await addData(data);
				break;
			case 'edit':
				res = await editData(data);
				break;
			case 'del':
				res = await delData(data);
				break;
			default:
				res = {
					code: 402,
					msg: '非法访问'
				}
				break;
		}
		return res;
	}
}

/**
 * 获取数据通过ID
 */
async function getDataById(data) {
	var result = await db.collection('address').where({
		'userId': data.userId
	}).get();
	return result.data
}
/**
 * 添加数据
 */
async function addData(data) {
	var res = {}
	var r1 = await db.collection('address').where({
		'userId': data.userId
	}).get();
	if (r1.data[0]) {
		let tmp = r1.data[0].data;
		if (data.addressData.default == true) { //说明是默认显示
			for (let i = 0; i < tmp.length; i++) {
				if (tmp[i].default == true) {
					tmp[i].default = false
				}
			}
		}
		tmp.push(data.addressData);
		const result = await db.collection('address').doc(r1.data[0]._id).update({
			userId: data.userId,
			data: tmp,
			updatetime: data.updatetime
		})
		res.data = result.data;
		res.code = 200;
	} else {
		let tmp = [];
		tmp.push(data.addressData);
		const result = await db.collection('address').add({
			userId: data.userId,
			data: tmp,
			updatetime: data.updatetime
		})
		res.data = result.data
		res.code = 200;
	}
	return res;
}
/**
 * 更新数据
 */
async function editData(data) {
	var res = {}
	var r1 = await db.collection('address').where({
		'userId': data.userId
	}).get();
	if (r1.data[0]) {
		let tmp = []
		for (var i = 0; i < r1.data[0].data.length; i++) {
			if (r1.data[0].data[i].default == true) {
				if (data.addressData.default == true) {
					r1.data[0].data[i].default = false;
				}
			}
			if (r1.data[0].data[i].id == data.addressData.id) {
				tmp.push(data.addressData)
			} else {
				tmp.push(r1.data[0].data[i])
			}
		}
		const result = await db.collection('address').doc(r1.data[0]._id).update({
			userId: data.userId,
			data: tmp,
			updatetime: data.updatetime
		})
		res.data = result.data
	} else {}
	res.code = 200;
	return res;
}
/**
 * @param {Object} data
 * 删除数据
 */
async function delData(data) {
	var res = {}
	var r1 = await db.collection('address').where({
		'userId': data.userId
	}).get();
	if (r1.data[0]) {
		let tmp = []
		for (var i = 0; i < r1.data[0].data.length; i++) {
			if (r1.data[0].data[i].id == data.addressId) {

			} else {
				tmp.push(r1.data[0].data[i])
			}
		}
		const result = await db.collection('address').doc(r1.data[0]._id).update({
			userId: data.userId,
			data: tmp,
			updatetime: data.updatetime
		})
		res.data = result.data
		res.code = 200
		res.msg = '删除成功'
	} else {
		res.code = 402
		res.msg = '删除失败'
	}
	return res
}
